﻿define(['app'], function(app) {
	'use strict';

	var controller = function controller($scope, Afpay, GoPage, $stateParams, GoDialog, GoPay, GoPicture, $timeout, $ionicModal) {
		//页面跳转-不能用go(-1)
		$scope.order_id = $stateParams.order_id;
		$scope.input = new Object();
		$scope.input.image = new Array();
		
		$scope.$on('$ionicView.afterEnter', function() {
			$scope.pay_app_id = "";
			$scope.init_data();
		}, false);
		
		$scope.order_items = new Object();
		$scope.order_items.payment = new Array();
		$scope.get_kind = function() {
			var kind = new Array();
			kind[0] = '';
			kind[1] = { 'name': '线下', 'logo': '' };
			kind[2] = { 'name': '预存款', 'logo': 'img/guilin/afsrue/pay03.png' };
			kind[3] = { 'name': '微信', 'logo': 'img/guilin/afsrue/pay01.png' };
			kind[null] = { 'name': '微信', 'logo': 'img/guilin/afsrue/pay01.png' };
			kind[4] = { 'name': '支付宝', 'logo': 'img/guilin/afsrue/pay02.png' };
			kind[5] = { 'name': '授信', 'logo': 'img/guilin/afsrue/pay04.png' };
			kind[6] = { 'name': '货到付款', 'logo': '' };
			kind[7] = { 'name': '微信', 'logo': 'img/guilin/afsrue/pay01.png' };
			for(var i = 0; i < $scope.afpay.pay_app.length; i++) {
				$scope.order_items.payment[i] = {
					"id": $scope.afpay.pay_app[i].pay_app_id,
					"logo": kind[$scope.afpay.pay_app[i].pay_app_id].logo,
					"name": kind[$scope.afpay.pay_app[i].pay_app_id].name,
					"checked": false
				}
			}
		}
		
		//微信内置浏览器
		$scope.isWeiXin = function() {
			var ua = window.navigator.userAgent.toLowerCase();
			if(ua.match(/MicroMessenger/i) == 'micromessenger') {
				return true;
			} else {
				return false;
			}
		}
		
		//初始化页面
		$scope.init_data = function() {
			var platform = "app";
			if(window.cordova && window.cordova.plugins) {
				platform = "app";
			} else {
				if($scope.isWeiXin()) {
					platform = "wx";
				} else {
					platform = "web";
				}
			}
			Afpay.get_afpay($scope.order_id, platform, function(data) {
//				console.log(data)
				$scope.afpay = data;
				$scope.get_kind();
			})
		}
		
		//选择支付方式
		$scope.checked = function(index) {
			for (var i=0;i<$scope.order_items.payment.length;i++) {
				$scope.order_items.payment[i].checked = false;
			}
			var data = $scope.order_items.payment[index];
			var pay_id = data.id;
			if(pay_id == 2) {//如果是预存款支付
				if($scope.afpay.disabled_reason== '未设支付密码'){//如果没有设置支付密码
					data.checked = false;
					GoDialog.alert("提示","请先去设置支付密码！",function(){
						GoPage.go_states('pay-password',{"order_id":$scope.order_id});
					});
					return;
				}
				if($scope.afpay.money>$scope.afpay.advance){//余额不足
					data.checked = false;
					GoDialog.alert("提示","对不起，您的余额不足！");
					return;
				}
			}
			data.checked = true;
			if(pay_id == 1)//线下支付
				$scope.isOutLine = true;
			else
				$scope.isOutLine = false;
			$scope.pay_app_id = pay_id;
		}
		
		//选择线下支付
		$scope.selectOutLine = function($event, index) {
			$scope.bank_id = $scope.afpay.bank[index].bank_no;
			var current = $event.target;
			var divs;
			if(current.nodeName == "DIV") {
				divs = current.parentNode.children;
			} else {
				divs = current.parentNode.parentNode.children;
			}
			for(var i = 0; i < divs.length; i++) {
				divs[i].children[0].style.display = "none";
			}
			if(divs[index].children[0].style.display == "block") {
				divs[i].children[0].style.display = "none";
			} else
				divs[index].children[0].style.display = "block";
		}

		/******************确认支付密码**************/
		$ionicModal.fromTemplateUrl("templates/modal/confirm_pay.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_confirm = modal;
		});
		//预存款支付
		$scope.openModal_confirm = function() {
			//每次打开modal，必须初始化以下2个变量
			$scope.isAfpay = true;//控制弹窗里文字的显示
			$scope.input.money = $scope.afpay.money;//金额
			$scope.input.password = "";
			$scope.showPotArr = new Array();
			$scope.modal_confirm.show();//满足输入条件，才弹窗
			$scope.getInputFocus();
		}
		$scope.closeModal_confirm = function(index) {
			$scope.modal_confirm.hide();
		}
		//获取焦点
		$scope.getInputFocus = function($event){
			if($event){
				$event.stopPropagation();//阻止事件冒泡
			}
			document.getElementById("inputPass").focus();
		}
		//输入密码监听
		$scope.$watch('input.password', function(newValue, oldValue) {
			$scope.showPotArr = new Array();//控制密码点的显示
			if(!newValue){
				return
			}
			if(newValue.length>6) {//6为密码
				newValue = newValue.substring(0, 6);
			}
			$scope.input.password = newValue;
			for (var i=0;i<$scope.input.password.length;i++) {
				$scope.showPotArr.push(i+1);
			}
			if($scope.input.password.length==6){//密码够6位，自动提交
				document.getElementById("inputPass").blur();//防止继续输入
				$scope.closeModal_confirm();
				$scope.go_pay();
//				console.log("提交："+$scope.input.password)
			}
		})
		/******************确认支付密码**************/
		
		//提交
		$scope.go_pay = function() {
			if(!$scope.pay_app_id){
				GoDialog.toast("请选择支付方式！");
					return;
			}
			if($scope.pay_app_id == 1) {//线下支付
				if($scope.input.image.length == 0) {
					GoDialog.toast("请上传凭证！");
					return;
				}
			} else
				$scope.bank_id = '';
			var order_id = JSON.parse($scope.order_id);
			if(order_id.length > 1) {
				var order = '';
				for(var i = 0; i < order_id.length; i++) {
					if(i != (order_id.length - 1))
						order += order_id[i] + ',';
					else
						order += order_id[i];
				}
				Afpay.go_pay_more(order, $scope.pay_app_id, $scope.input.image[0], $scope.bank_id, $scope.input.password, function(data) {
					if(data.success == true) {
						if($scope.pay_app_id == 3 || $scope.pay_app_id == 4 || $scope.pay_app_id == 7) {
							var pay_id = $scope.pay_app_id == 3 ? 1 : ($scope.pay_app_id == 7 ? 1 : 2);
							GoPay.do_pay(data.result.pay_fields, pay_id, function(data) {
								GoDialog.toast('支付成功');
								$timeout(function() {
//									GoPage.go_states_back("afall", { "type": 2 });
									GoPage.go_states_back("predepositresult",{'isSuccess':true,'payType':$scope.pay_app_id,'money':$scope.afpay.money,'isAfpay':true});
								}, 3000)
							})
						} else {
							GoDialog.toast('支付成功');
							GoPage.go_states_back("predepositresult",{'isSuccess':true,'payType':$scope.pay_app_id,'money':$scope.afpay.money,'isAfpay':true});
//							GoPage.go_states_back("afall", { "type": 2 });
						}
					} else{
//						GoDialog.alert("提示",data.msg);
						GoPage.go_states_back("predepositresult",{'isSuccess':false,'payType':$scope.pay_app_id,'money':$scope.afpay.money,'failReason':data.msg,'isAfpay':true,'order_id':$scope.order_id});
					}
				})
			} else {
				Afpay.go_pay($scope.order_id, $scope.pay_app_id, $scope.input.image[0], $scope.bank_id, $scope.input.password, function(data) {
					if(data.success == true) {
						if($scope.pay_app_id == 3 || $scope.pay_app_id == 4 || $scope.pay_app_id == 7) {
							var pay_id = $scope.pay_app_id == 3 ? 1 : ($scope.pay_app_id == 7 ? 1 : 2);
							GoPay.do_pay(data.result.pay_fields, pay_id, function(data) {
								GoDialog.toast('支付成功');
								$timeout(function() {
//									GoPage.go_states_back("afall", { "type": 2 });
									GoPage.go_states_back("predepositresult",{'isSuccess':true,'payType':$scope.pay_app_id,'money':$scope.afpay.money,'isAfpay':true});
								}, 3000)
							})
						} else {
							GoDialog.toast('支付成功');
//							GoPage.go_states_back("afall", { "type": 2 });
							GoPage.go_states_back("predepositresult",{'isSuccess':true,'payType':$scope.pay_app_id,'money':$scope.afpay.money,'isAfpay':true});
						}
					} else{
//						GoDialog.alert("提示",data.msg);
						GoPage.go_states_back("predepositresult",{'isSuccess':false,'payType':$scope.pay_app_id,'money':$scope.afpay.money,'failReason':data.msg,'isAfpay':true,'order_id':$scope.order_id});
					}
				})
			}
		};
		
		
		/****************图片处理*******************/
		$scope.ondelete = function(index) {
			$scope.input.image.splice(index, 1);
		};
		//动态响应
		$scope.doShowFile = function() {
			document.getElementById("afpay-upfilebutton").click();
		}
		//图片上传
		$scope.onupload = function(val) {
			var fileList = val.files;
			for(var i = 0; i < val.files.length; i++) {
				var reader = new FileReader();
				reader.readAsDataURL(fileList[i]);
				var file = fileList[i];
				reader.onload = function(e) {
					//图片进行压缩处理
					GoPicture.compress(file,e.target.result, 50, function(base64) {
						$scope.$apply(function() {
							var i = $scope.input.image.length;
							$scope.input.image[0] = {
								"image": base64
							}
							val.value = "";
						});
					});
				}
			}
		};
		
		$scope.openFileActSheet = function() {
			var buttons = new Array();
			buttons.push({ text: '删除图片', style: '' });
			buttons.push({ text: '显示大图', style: '' });

			GoDialog.sheet('图片操作', '取消', buttons, function(bindex) {
				if(bindex == 0) {
					GoDialog.confirm('删除图片', '是否要删除该图片？', function() {
						$timeout(function() {
							var s = $scope.input.image;
							s.id = null;
							s.image = null;
						}, 1);
					})
				} else if(bindex == 1) {//查看大图
					GoDialog.showBigImg($scope.input.image[0].image);
				}
				return true;
			});
		}
		/****************图片处理*******************/


	}

	controller.$inject = ['$scope', 'Afpay', 'GoPage', '$stateParams', 'GoDialog', 'GoPay', 'GoPicture', '$timeout','$ionicModal'];

	return app.registerController("afpayctrl", controller);
});